import { onUnmounted, ref } from 'vue';
import AMapLoader from '@amap/amap-jsapi-loader';
import { AMAP_MAP_SECURITY_KEY, mapConfig, mapOptions } from '@/constants/amap';
import { polylineOptions } from '@/hooks/common/amap';

export const useMap = ({ domId }: { domId: string } = { domId: 'mapContainer' }) => {
  const map = ref();
  const AMap = ref();
  const infoWindow = ref();

  /** 初始化地图 */
  async function initMap() {
    try {
      // eslint-disable-next-line no-underscore-dangle
      (window as any)._AMapSecurityConfig = {
        // 二者选其一，无serviceHost就优先使用securityJsCode
        // 高德地图密匙
        securityJsCode: AMAP_MAP_SECURITY_KEY
        // 后台远程服务地址
        // serviceHost: AMAP_MAP_SERVICE_HOST
      };
      AMap.value = await AMapLoader.load({ ...mapConfig });
      map.value = domId && new AMap.value.Map(domId, mapOptions);

      infoWindow.value = new AMap.value.InfoWindow({
        isCustom: true, // 使用自定义窗体
        content: document.createElement('div'),
        offset: new AMap.value.Pixel(0, -30)
      });
    } catch {
      window.$message?.error('地图初始化失败');
    }
  }

  // 关闭信息窗体
  function closeInfoWindow() {
    map.value.clearInfoWindow();
  }

  function markerClick(e: any) {
    infoWindow.value.setContent(e.target.content);
    infoWindow.value.open(map.value, e.target.getPosition());
  }

  /** 添加点 */
  function addMarker({
    position = [],
    title = '',
    icon = new URL('@/assets/images/amap/device.png', import.meta.url).href,
    content
  }: {
    position: number[];
    title: string;
    icon?: string;
    content?: HTMLElement;
  }) {
    const marker = new AMap.value.Marker({
      map: map.value,
      position,
      icon,
      offset: new AMap.value.Pixel(-13, -30),
      title
    });
    if (content) {
      marker.content = content;
      marker.on('click', markerClick);
    }
  }

  /** 添加线 */
  function addPolyline(options: object = {}) {
    return new AMap.value.Polyline({
      map: map.value,
      ...polylineOptions,
      ...options
    });
  }

  /** 地点搜索 */
  function placeSearch<T>(city: string, keyword: string) {
    return new Promise<T[]>(resolve => {
      AMap.value.plugin('AMap.PlaceSearch', () => {
        const mapPlaceSearch = new AMap.value.PlaceSearch({
          city
        });
        mapPlaceSearch.search(keyword, (_status: any, result: any) => {
          if (result.info === 'OK') {
            resolve(result.poiList.pois);
          } else {
            resolve([]);
          }
        });
      });
    });
  }

  /** 设置地图缩放和平移中心 */
  function setZoomAndCenter(zoom: number, position: number[]) {
    map.value.setZoomAndCenter(zoom, position);
  }

  /** 销毁地图 */
  function destroyMap() {
    map.value?.destroy();
  }

  onUnmounted(() => {
    destroyMap();
  });

  return { AMap, map, initMap, addMarker, addPolyline, closeInfoWindow, placeSearch, setZoomAndCenter };
};

export * from '@/constants/amap';
